package com.daily.daily_push;

import io.kubernetes.client.custom.Quantity;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.Config;
import io.kubernetes.client.util.KubeConfig;
import io.kubernetes.client.util.Yaml;
import lombok.var;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@org.springframework.context.annotation.Configuration
public class KubernetesClientExample {
    public KubernetesClientExample() throws ApiException {
    }

    public static void main(String[] args) throws IOException, ApiException {

// 从配置文件中加载 Kubernetes 配置
        ApiClient client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader("D:\\commonTest\\k8s\\config.yaml"))).build();
        // 设置默认客户端实例
        Configuration.setDefaultApiClient(client);
//============================================================
        // 创建 CoreV1Api 实例
        CoreV1Api api = new CoreV1Api();
        // 在此处编写你的 Kubernetes 操作代码
        // 例如，获取所有的 Pods 列表
        V1PodList list = api.listNamespacedPod("mcn", null, null, null,
                null, null, null, null, null,null,null);
        List<V1Pod> items = list.getItems();
        // 输出 Pods 列表
        for (var item : list.getItems()) {
            System.out.println(item.getMetadata().getName());
        }


        //1、获取指定命名空间和 Pod的日志
        //指定命名空间和 Pod 名称，必填
        String namespace = "mcn";
        String podName = "web-96d5df5c8-rpsnk";
        //选填
        String container = "nginx";

        // 获取 Pod 日志
        String log = api.readNamespacedPodLog(podName, namespace, container, null, null, null, null, null, null, null,null);
        System.out.println(log);


        //2、查询命名空间列表
        // 调用 listNamespace 方法
        V1NamespaceList listNamespace = api.listNamespace("true", null, null, null, null, null, null, null, null,null);

        List<V1Namespace> items3 = listNamespace.getItems();
        // 打印命名空间名称
        for (var item : listNamespace.getItems()) {
            System.out.println("打印命名空间名称 :" +item.getMetadata().getName());
        }

        //3、查询指定命名空间的详细信息
        V1Namespace reaNamespace = api.readNamespace("default", "true");
        System.out.println("查询指定命名空间的详细信息: "+reaNamespace);


        //4、创建pod，通过参数创建
        V1Pod pod = new V1Pod()
                .metadata(new V1ObjectMeta().name("my-pod"))
                .spec(new V1PodSpec()
                        .containers(Arrays.asList(
                                new V1Container()
                                        .name("my-container")
                                        .image("busybox")
                                        .ports(Arrays.asList(
                                                new V1ContainerPort().containerPort(80)
                                        ))
                        ))
                );

        V1Pod createdPod = api.createNamespacedPod("default", pod, null, null, null,null);
        System.out.println(createdPod);
    //5、创建pod，通过yaml deployment创建 409 已创建

        AppsV1Api appsV1Api = new AppsV1Api();
        File file = new File("D:\\commonTest\\k8s\\my01.yaml");
        System.out.println(file);
        V1Deployment pod1 = (V1Deployment) Yaml.load(file);

        V1Deployment createdPod1 = null;
        try {
            createdPod1 = appsV1Api.createNamespacedDeployment("default", pod1, "true", null, null,null);
        } catch (ApiException e) {
            System.err.println(e.getResponseBody());
            e.printStackTrace();
        }
        System.out.println("创建pod，通过yaml创建:  "+ createdPod1);



      //6、删除pod，通过指定命名空间和pod名称,无法删除deployment
//        CoreV1Api api2 = new CoreV1Api();
//        V1DeleteOptions deleteOptions = new V1DeleteOptions();
//        V1Pod status = api2.deleteNamespacedPod("web01-5d8cdc9646-hnqst", "default","true", null, null, null, null, deleteOptions);
//        System.out.println("删除pod: "+status);


        //6、查询pod列表

        CoreV1Api api2 = new CoreV1Api();
        V1PodList v1PodList = api2.listNamespacedPod("default", "true", null, null, null, null, null, null, null, null, null);
        List<V1Pod> items1 = v1PodList.getItems();
        for (V1Pod item : v1PodList.getItems()) {
            System.out.println("查询pod列表: "+ item.getMetadata().getName());
        }
//6、删除deployment，通过指定命名空间和pod名称
      /*  AppsV1Api api3 = new AppsV1Api();

        V1DeleteOptions deleteOptions3 = new V1DeleteOptions();
        V1Status status3 = api3.deleteNamespacedDeployment("web01", "default", "true", null, null, null, null, deleteOptions3);
        System.out.println("删除deployment"+status3);*/


//6、查询deployment，通过指定命名空间和pod名称
        AppsV1Api api4 = new AppsV1Api();
        V1DeploymentList list4 = api4.listNamespacedDeployment("default", "true", null, null, null, null, null, null, null, null,null);
        List<V1Deployment> items2 = list4.getItems();
        for (V1Deployment item : list4.getItems()) {
            System.out.println("查询deployment :"+item.getMetadata().getName());
        }

//7、查询node节点
        CoreV1Api apiInstance = new CoreV1Api();
        V1NodeList v1NodeList = apiInstance.listNode("true", null, null, null, null, null, null, null, null, null);
        for (V1Node item : v1NodeList.getItems()) {
            System.out.println("查询node节点: " + item .getMetadata().getName());
        }

        CoreV1Api api5 = new CoreV1Api();
//查询node节点的详细信息
        V1NodeList list5 = api5.listNode(null, null, null, null, null, null, null, null, null,null);
        for (V1Node item : list5.getItems()) {
            System.out.println("Name: " + item.getMetadata().getName());
            System.out.println("Labels: " + item.getMetadata().getLabels());
            System.out.println("Creation Timestamp: " + item.getMetadata().getCreationTimestamp());
            System.out.println("Taints: " + item.getSpec().getTaints());

            Map<String, Quantity> allocatable = item.getStatus().getAllocatable();
            System.out.println("Allocatable CPU: " + allocatable.get("cpu"));
            System.out.println("Allocatable Memory: " + allocatable.get("memory"));
            System.out.println("Allocatable Pods: " + allocatable.get("pods"));
            V1NodeSystemInfo nodeInfo1 = item.getStatus().getNodeInfo();
            String kernelVersion = nodeInfo1.getKernelVersion();
            String kernelVersion1 = nodeInfo1.getKernelVersion();
            String machineID = nodeInfo1.getMachineID();
//            System.out.println("Architecture: " + nodeInfo.get("architecture"));
//            System.out.println("Container Runtime Version: " + nodeInfo.get("containerRuntimeVersion"));
//            System.out.println("Kernel Version: " + nodeInfo.get("kernelVersion"));
//            System.out.println("Kubelet Version: " + nodeInfo.get("kubeletVersion"));
//            System.out.println("Operating System: " + nodeInfo.get("operatingSystem"));
//            System.out.println("OS Image: " + nodeInfo.get("osImage"));
            System.out.println();
        }

        //查询cpu等信息

        CoreV1Api api6 = new CoreV1Api();

        int nodeCount = 0;
        int totalCpu = 0;
        Long totalMemory = 0L;

        V1NodeList list6 = api6.listNode(null, null, null, null, null, null, null, null, null,null  );
        for (V1Node item : list6.getItems()) {
            nodeCount++;
            Map<String, Quantity> allocatable = item.getStatus().getAllocatable();
            totalCpu += Integer.parseInt(allocatable.get("cpu").getNumber().toString());
            totalMemory += Long.parseLong(allocatable.get("memory").getNumber().toString());
        }


        CoreV1Api api7 = new CoreV1Api();

        V1NodeList list7 = api7.listNode(null, null, null, null, null, null, null, null, null,null);
        for (V1Node item : list7.getItems()) {
            System.out.println("Name: " + item.getMetadata().getName());
            for (V1NodeCondition condition : item.getStatus().getConditions()) {
                if ("Ready".equals(condition.getType())) {
                    System.out.println("Status: " + condition.getStatus());
                }
            }
            System.out.println();
        }

        //8 查询configMap
        CoreV1Api api8 = new CoreV1Api();

        // 指定ConfigMap的命名空间和名称
        String namespace8 = "your-namespace";
        String configMapName = "your-configmap-name";

        // 查询ConfigMap
        V1ConfigMap configMap = api8.readNamespacedConfigMap(configMapName, namespace8, "true");

        // 打印ConfigMap的数据
        System.out.println("ConfigMap data:");
        configMap.getData().forEach((key, value) -> System.out.println(key + ": " + value));

//8 查询secret

        // 创建CoreV1Api实例
        CoreV1Api api9 = new CoreV1Api();

        // 指定Secret的命名空间和名称
        String namespace9 = "your-namespace";
        String secretName9 = "your-secret-name";

        // 查询Secret
        V1Secret secret = api.readNamespacedSecret(secretName9, namespace9, null);

        // 打印Secret的数据
        System.out.println("Secret data:");
        secret.getData().forEach((key, value) -> {
            String decodedValue = new String(java.util.Base64.getDecoder().decode(value));
            System.out.println(key + ": " + decodedValue);
        });
    }
}
